package com.hzit.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzit.dto.CategoryDTO;
import com.hzit.entity.Category;
import com.hzit.entity.CategoryKind;
import com.hzit.mapper.CategoryMapper;
import com.hzit.service.ICategoryKindService;
import com.hzit.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.utils.PageResult;
import com.hzit.vo.SearchVO;
import org.checkerframework.checker.units.qual.A;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-31
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    @Autowired
    private ICategoryKindService categoryKindService;

    @Override
    public PageResult<CategoryDTO> search(Integer page, Integer pageSize, SearchVO searchVO) {
        QueryWrapper<Category> queryWrapper=new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(searchVO.getTitle()),"title",searchVO.getTitle())
                .eq(searchVO.getCategoryId()!=null && searchVO.getCategoryId()!=0,"category_id",searchVO.getCategoryId());
        Page<Category> categoryPage = this.baseMapper.selectPage(new Page<>(page, pageSize), queryWrapper);
        List<Category> records = categoryPage.getRecords();
        List<CategoryDTO> list=new ArrayList<>();
        records.stream().map(m->{
            CategoryDTO dto=new CategoryDTO();
            BeanUtils.copyProperties(m,dto);
            CategoryKind byId = categoryKindService.getById(m.getCategoryId());
            dto.setCategoryName(byId.getName());
            list.add(dto);
            return m;
        }).collect(Collectors.toList());
        return new PageResult<>(categoryPage.getTotal(),list);
    }
}
